<template>
  <div class="users-page" :class="{ dark: isDark }">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-content">
        <h1 class="page-title">用户管理</h1>
        <p class="page-description">管理系统用户和权限</p>
      </div>
      <div class="header-actions">
        <el-button type="primary" @click="showCreateModal" class="create-btn">
          <el-icon><Plus /></el-icon>
          新建用户
        </el-button>
      </div>
    </div>

    <!-- 统计卡片 -->
    <div class="stats-cards">
      <el-card class="stat-card" shadow="hover">
        <div class="stat-content">
          <div class="stat-icon total">
            <el-icon><User /></el-icon>
          </div>
          <div class="stat-info">
            <div class="stat-value">{{ totalUsers }}</div>
            <div class="stat-label">总用户数</div>
          </div>
        </div>
      </el-card>

      <el-card class="stat-card" shadow="hover">
        <div class="stat-content">
          <div class="stat-icon active">
            <el-icon><Check /></el-icon>
          </div>
          <div class="stat-info">
            <div class="stat-value">{{ activeUsers }}</div>
            <div class="stat-label">活跃用户</div>
          </div>
        </div>
      </el-card>

      <el-card class="stat-card" shadow="hover">
        <div class="stat-content">
          <div class="stat-icon admin">
            <el-icon><Star /></el-icon>
          </div>
          <div class="stat-info">
            <div class="stat-value">{{ adminUsers }}</div>
            <div class="stat-label">管理员</div>
          </div>
        </div>
      </el-card>

      <el-card class="stat-card" shadow="hover">
        <div class="stat-content">
          <div class="stat-icon editor">
            <el-icon><Edit /></el-icon>
          </div>
          <div class="stat-info">
            <div class="stat-value">{{ editorUsers }}</div>
            <div class="stat-label">编辑者</div>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 搜索和筛选 -->
    <el-card class="search-card" shadow="never">
      <div class="search-container">
        <div class="search-filters">
          <el-input
            v-model="searchText"
            placeholder="搜索用户名或邮箱..."
            clearable
            style="width: 300px"
            @input="handleSearch"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>

          <el-select
            v-model="roleFilter"
            placeholder="角色筛选"
            clearable
            style="width: 150px"
            @change="handleFilter"
          >
            <el-option label="管理员" value="admin" />
            <el-option label="编辑者" value="user" />
          </el-select>

          <el-select
            v-model="statusFilter"
            placeholder="状态筛选"
            clearable
            style="width: 150px"
            @change="handleFilter"
          >
            <el-option label="活跃" value="active" />
            <el-option label="禁用" value="inactive" />
          </el-select>

          <el-button @click="resetFilters">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </div>
      </div>
    </el-card>

    <!-- 用户列表 -->
    <el-card class="table-card" shadow="never">
      <el-table
        :data="filteredUsers"
        :loading="loading"
        :style="{ width: '100%' }"
        v-loading="loading"
      >
        <el-table-column label="用户信息" align="center">
          <template #default="{ row }">
            <div class="user-info">
              <div class="user-avatar">
                <el-avatar :src="row.avatar_url" :size="40">
                  {{ row.username.charAt(0).toUpperCase() }}
                </el-avatar>
              </div>
              <div class="user-details">
                <div class="username">{{ row.username }}</div>
                <div class="email">{{ row.email }}</div>
              </div>
            </div>
          </template>
        </el-table-column>

        <el-table-column label="角色" align="center">
          <template #default="{ row }">
            <el-tag :type="row.role === 'admin' ? 'danger' : 'primary'">
              {{ getRoleText(row.role) }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column label="状态" align="center">
          <template #default="{ row }">
            <el-tag :type="row.status === 'active' ? 'success' : 'info'">
              {{ row.status === "active" ? "活跃" : "禁用" }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column prop="lastLoginAt" label="最后登录" align="center">
          <template #default="{ row }">
            <span v-if="row.lastLoginAt" class="last-login">
              {{ formatDate(row.lastLoginAt) }}
            </span>
            <span v-else class="text-muted">从未登录</span>
          </template>
        </el-table-column>

        <el-table-column prop="createdAt" label="创建时间" align="center">
          <template #default="{ row }">
            <span class="created-at">{{ formatDate(row.createdAt) }}</span>
          </template>
        </el-table-column>

        <el-table-column label="操作" align="center" fixed="right">
          <template #default="{ row }">
            <div class="action-buttons">
              <el-button
                type="primary"
                link
                size="small"
                @click="editUser(row)"
              >
                <el-icon><Edit /></el-icon>
                编辑
              </el-button>
              <el-button
                type="warning"
                link
                size="small"
                @click="toggleUserStatus(row)"
              >
                <el-icon><Switch /></el-icon>
                {{ row.status === "active" ? "禁用" : "启用" }}
              </el-button>
              <el-popconfirm
                title="确定要删除这个用户吗？"
                @confirm="deleteUser(row.id)"
              >
                <template #reference>
                  <el-button type="danger" link size="small">
                    <el-icon><Delete /></el-icon>
                    删除
                  </el-button>
                </template>
              </el-popconfirm>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 创建/编辑用户模态框 -->
    <el-dialog
      v-model="modalVisible"
      :title="editingUser ? '编辑用户' : '新建用户'"
      width="600px"
      :before-close="handleCancel"
    >
      <el-form
        :model="userForm"
        :rules="rules"
        ref="formRef"
        label-width="80px"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="用户名" prop="username">
              <el-input
                v-model="userForm.username"
                placeholder="请输入用户名"
                maxlength="20"
                show-word-limit
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="userForm.email" placeholder="请输入邮箱" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="角色" prop="role">
              <el-select
                v-model="userForm.role"
                placeholder="选择用户角色"
                style="width: 100%"
              >
                <el-option label="管理员" value="admin" />
                <el-option label="编辑者" value="user" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-select
                v-model="userForm.status"
                placeholder="选择用户状态"
                style="width: 100%"
              >
                <el-option label="活跃" value="active" />
                <el-option label="禁用" value="inactive" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item v-if="!editingUser" label="密码" prop="password">
          <el-input
            v-model="userForm.password"
            type="password"
            placeholder="请输入密码"
            show-password
          />
        </el-form-item>

        <el-form-item label="头像">
          <div class="avatar-upload-container">
            <el-input
              v-model="userForm.avatar"
              placeholder="请输入头像文件ID（可选）"
              style="margin-bottom: 12px"
            />
            <div class="avatar-preview">
              <el-avatar 
                v-if="userForm.avatar" 
                :src="`/api/file/${userForm.avatar}`" 
                :size="60"
              >
                {{ userForm.username?.charAt(0).toUpperCase() }}
              </el-avatar>
              <el-avatar v-else :size="60">
                {{ userForm.username?.charAt(0).toUpperCase() }}
              </el-avatar>
            </div>
            <div class="upload-hint">
              <el-text size="small" type="info">
                提示：请在媒体库中选择文件后，将文件ID填入上方输入框
              </el-text>
            </div>
          </div>
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleCancel">取消</el-button>
          <el-button type="primary" @click="handleSubmit" :loading="submitting">
            {{ editingUser ? "更新" : "创建" }}
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import type { AdminUser } from "~/types/admin";
import { ElMessage } from "element-plus";

// 图标导入
const { Plus, User, Check, Star, Edit, Search, Refresh, Switch, Delete } =
  await import("@element-plus/icons-vue");

// 暗色模式支持
const colorMode = useColorMode();
const isDark = computed(() => colorMode.value === "dark");

// 响应式数据
const loading = ref(false);
const modalVisible = ref(false);
const submitting = ref(false);
const editingUser = ref<AdminUser | null>(null);
const searchText = ref("");
const roleFilter = ref<string>();
const statusFilter = ref<string>();
const formRef = ref();

// 用户表单
const userForm = ref({
  username: "",
  email: "",
  password: "",
  role: "user" as "admin" | "user",
  status: "active" as "active" | "inactive",
  avatar: null as number | null,
});

// 表单验证规则
const rules = computed(() => ({
  username: [
    { required: true, message: "请输入用户名", trigger: "blur" },
    { min: 3, max: 20, message: "用户名长度为3-20个字符", trigger: "blur" },
  ],
  email: [
    { required: true, message: "请输入邮箱", trigger: "blur" },
    {
      type: "email" as const,
      message: "请输入有效的邮箱地址",
      trigger: "blur",
    },
  ],
  password: [
    {
      required: !editingUser.value,
      message: "请输入密码",
      trigger: "blur",
    },
    {
      validator: (rule: any, value: string, callback: Function) => {
        if (!value && editingUser.value) {
          callback();
          return;
        }
        if (value && value.length < 6) {
          callback(new Error("密码长度不能少于6位"));
          return;
        }
        callback();
      },
      trigger: "blur",
    },
  ],
  role: [{ required: true, message: "请选择用户角色", trigger: "change" }],
  status: [{ required: true, message: "请选择用户状态", trigger: "change" }],
}));

// 用户数据
const users = ref<AdminUser[]>([]);

// 分页配置
const pagination = ref({
  current: 1,
  pageSize: 10,
  total: 0,
});

// 计算属性
const totalUsers = computed(() => users.value.length);
const activeUsers = computed(
  () => users.value.filter((user) => user.status === "active").length
);
const adminUsers = computed(
  () => users.value.filter((user) => user.role === "admin").length
);
const editorUsers = computed(
  () => users.value.filter((user) => user.role === "user").length
);

// 计算属性：过滤后的用户
// 注意：现在使用服务端分页，所以不再需要客户端过滤和分页逻辑
const filteredUsers = computed(() => users.value);

// 方法
const getRoleText = (role: string) => {
  const texts = {
    admin: "管理员",
    editor: "编辑者",
    user: "编辑者", // API返回的角色是'user'，但UI显示的是'编辑者'
  };
  return texts[role as keyof typeof texts] || role;
};

const formatDate = (date: string) => {
  return new Date(date).toLocaleDateString("zh-CN", {
    year: "numeric",
    month: "2-digit",
    day: "2-digit",
    hour: "2-digit",
    minute: "2-digit",
  });
};

const showCreateModal = () => {
  editingUser.value = null;
  userForm.value = {
    username: "",
    email: "",
    password: "",
    role: "user",
    status: "active",
    avatar: null,
  };
  modalVisible.value = true;
};

const editUser = (user: AdminUser) => {
  editingUser.value = user;
  userForm.value = {
    username: user.username,
    email: user.email,
    password: "",
    role: user.role as "admin" | "user",
    status: user.status,
    avatar: user.avatar || null,
  };
  modalVisible.value = true;
};

const handleSubmit = async () => {
  try {
    await formRef.value?.validate();
    submitting.value = true;

    if (editingUser.value) {
      // 编辑用户 - 构建API请求体
      const updateData: any = {
        username: userForm.value.username,
        email: userForm.value.email,
        role: userForm.value.role, // 直接使用表单中的角色值
        status: userForm.value.status,
        avatar: userForm.value.avatar,
      };

      // 只有当用户输入了新密码时才包含密码字段
      if (userForm.value.password) {
        updateData.password = userForm.value.password;
      }

      const { success, message } = await $fetch<{
        success: boolean;
        message: string;
      }>(`/api/admin/users/${editingUser.value.id}`, {
        method: "PUT",
        body: updateData,
      });

      if (success) {
        ElMessage.success("用户更新成功！");
        await fetchUsers(); // 重新获取用户列表
      } else {
        throw new Error(message || "更新失败");
      }
    } else {
      // 新建用户 - 构建API请求体
      const createData = {
        username: userForm.value.username,
        email: userForm.value.email,
        password: userForm.value.password,
        nickname: userForm.value.username, // 使用用户名作为昵称
        role: userForm.value.role, // 直接使用表单中的角色值
        status: userForm.value.status,
        avatar: userForm.value.avatar,
        bio: "",
      };

      const { success, message } = await $fetch("/api/admin/users", {
        method: "POST",
        body: createData,
      });

      if (success) {
        ElMessage.success("用户创建成功！");
        await fetchUsers(); // 重新获取用户列表
      } else {
        throw new Error(message || "创建失败");
      }
    }

    modalVisible.value = false;
  } catch (error: any) {
    console.error("操作失败:", error);
    ElMessage.error(error.data?.message || error.message || "操作失败");
  } finally {
    submitting.value = false;
  }
};

const handleCancel = () => {
  modalVisible.value = false;
  formRef.value?.resetFields();
};

// 切换用户状态
const toggleUserStatus = async (user: AdminUser) => {
  try {
    const newStatus = user.status === "active" ? "inactive" : "active";
    const { success, message } = await $fetch<{
      success: boolean;
      message: string;
    }>(`/api/admin/users/${user.id}`, {
      method: "PUT",
      body: { status: newStatus },
    });

    if (success) {
      ElMessage.success(
        `用户已${user.status === "active" ? "禁用" : "启用"}！`
      );
      await fetchUsers(); // 重新获取用户列表
    } else {
      throw new Error(message || "状态切换失败");
    }
  } catch (error: any) {
    console.error("状态切换失败:", error);
    ElMessage.error(error.data?.message || error.message || "状态切换失败");
  }
};

// 删除用户
const deleteUser = async (id: string) => {
  try {
    const { success, message } = await $fetch<{
      success: boolean;
      message: string;
    }>(`/api/admin/users/${id}`, {
      method: "DELETE",
    });

    if (success) {
      ElMessage.success("用户删除成功！");
      await fetchUsers(); // 重新获取用户列表
    } else {
      throw new Error(message || "删除失败");
    }
  } catch (error: any) {
    console.error("删除失败:", error);
    ElMessage.error(error.data?.message || error.message || "删除失败");
  }
};

const handleSearch = () => {
  pagination.value.current = 1;
  fetchUsers();
};

const handleFilter = () => {
  pagination.value.current = 1;
  fetchUsers();
};

const resetFilters = () => {
  searchText.value = "";
  roleFilter.value = undefined;
  statusFilter.value = undefined;
  pagination.value.current = 1;
  fetchUsers();
};

const handleSizeChange = (size: number) => {
  pagination.value.pageSize = size;
  pagination.value.current = 1;
  fetchUsers();
};

const handleCurrentChange = (current: number) => {
  pagination.value.current = current;
  fetchUsers();
};

// 获取用户数据
const fetchUsers = async () => {
  try {
    loading.value = true;
    const query = {
      page: pagination.value.current,
      pageSize: pagination.value.pageSize,
      search: searchText.value,
    };

    const {
      success,
      data,
      pagination: paginations,
    } = await $fetch<{
      success: boolean;
      data: any[];
      pagination: any;
    }>("/api/admin/users?" + new URLSearchParams(query as any).toString());

    if (success) {
      // 处理API返回的数据，确保符合AdminUser接口
      users.value = data.map((user: any) => ({
        id: user.id.toString(),
        username: user.username,
        email: user.email,
        role: user.role as "admin" | "user",
        status: user.status as "active" | "inactive",
        avatar: user.avatar || 0,
        avatar_url: user.avatar_url || "",
        createdAt: user.created_at,
        updatedAt: user.updated_at,
        lastLogin: user.lastLogin,
      }));

      pagination.value.total = paginations?.total || data.length;
    }
  } catch (error: any) {
    console.error("获取用户数据失败:", error);
    ElMessage.error(error.data?.message || "获取用户数据失败");
  } finally {
    loading.value = false;
  }
};

// 页面加载时获取数据
onMounted(() => {
  fetchUsers();
});

// 页面元数据
useHead({
  title: "用户管理 - 博客管理系统",
});
</script>

<style scoped>
.users-page {
  min-height: 100vh;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 24px;
  animation: fadeInDown 0.6s ease-out;
}

.header-content h1 {
  font-size: 28px;
  font-weight: 700;
  margin: 0 0 8px 0;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

.header-content p {
  color: #666;
  margin: 0;
  font-size: 14px;
}

.create-btn {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
  border-radius: 8px;
  padding: 12px 24px;
  font-weight: 600;
  transition: all 0.3s ease;
  box-shadow: 0 4px 15px rgba(102, 126, 234, 0.3);
}

.create-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(102, 126, 234, 0.4);
}

/* 统计卡片 */
.stats-cards {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(240px, 1fr));
  gap: 16px;
  margin-bottom: 24px;
  animation: fadeInUp 0.6s ease-out 0.2s both;
}

.stat-card {
  border-radius: 12px;
  border: none;
  transition: all 0.3s ease;
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
}

.stat-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15);
}

.stat-content {
  display: flex;
  align-items: center;
  padding: 8px;
}

.stat-icon {
  width: 48px;
  height: 48px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 16px;
  font-size: 24px;
  color: white;
}

.stat-icon.total {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.stat-icon.active {
  background: linear-gradient(135deg, #4caf50 0%, #45a049 100%);
}

.stat-icon.admin {
  background: linear-gradient(135deg, #ff9800 0%, #f57c00 100%);
}

.stat-icon.editor {
  background: linear-gradient(135deg, #2196f3 0%, #1976d2 100%);
}

.stat-value {
  font-size: 24px;
  font-weight: 700;
  color: #333;
  line-height: 1;
}

.stat-label {
  font-size: 14px;
  color: #666;
  margin-top: 4px;
}

/* 搜索卡片 */
.search-card {
  border-radius: 12px;
  margin-bottom: 24px;
  border: none;
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  animation: fadeInUp 0.6s ease-out 0.4s both;
}

.search-container {
  padding: 8px 0;
}

.search-filters {
  display: flex;
  gap: 12px;
  align-items: center;
  flex-wrap: wrap;
}

/* 表格卡片 */
.table-card {
  border-radius: 12px;
  border: none;
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  animation: fadeInUp 0.6s ease-out 0.6s both;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.user-avatar {
  flex-shrink: 0;
}

.user-details {
  display: flex;
  flex-direction: column;
}

.username {
  font-weight: 600;
  color: #333;
  margin-bottom: 2px;
}

.email {
  font-size: 12px;
  color: #666;
}

.last-login,
.created-at {
  font-size: 14px;
  color: #666;
}

.text-muted {
  color: #999;
  font-style: italic;
}

.action-buttons {
  display: flex;
  gap: 8px;
  justify-content: center;
}

.pagination-container {
  margin-top: 24px;
  display: flex;
  justify-content: center;
}

/* 暗色主题支持 */
.dark .header-content p {
  color: #d1d5db;
}

.dark .stat-card,
.dark .search-card,
.dark .table-card {
  background: rgba(30, 41, 59, 0.95);
  border: 1px solid rgba(71, 85, 105, 0.5);
}

.dark .stat-card:hover,
.dark .search-card:hover,
.dark .table-card:hover {
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.4);
}

.dark .stat-value {
  color: #f1f5f9;
}

.dark .stat-label {
  color: #94a3b8;
}

.dark .username {
  color: #f1f5f9;
}

.dark .email,
.dark .last-login,
.dark .created-at {
  color: #94a3b8;
}

.dark .text-muted {
  color: #64748b;
}

/* 动画效果 */
@keyframes fadeInDown {
  from {
    opacity: 0;
    transform: translateY(-20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

@keyframes fadeInUp {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

/* 头像上传区域样式 */
.avatar-upload-container {
  width: 100%;
}

.avatar-preview {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
}

.upload-hint {
  margin-top: 8px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .users-page {
    padding: 16px;
  }

  .page-header {
    flex-direction: column;
    gap: 16px;
    text-align: center;
  }

  .stats-cards {
    grid-template-columns: 1fr;
  }

  .search-filters {
    flex-direction: column;
    align-items: stretch;
  }

  .search-filters :deep(.el-input),
  .search-filters :deep(.el-select) {
    width: 100% !important;
  }

  .action-buttons {
    flex-direction: column;
    gap: 4px;
  }

  .user-info {
    flex-direction: column;
    text-align: center;
    gap: 8px;
  }
}

@media (max-width: 480px) {
  .stat-content {
    flex-direction: column;
    text-align: center;
  }

  .stat-icon {
    margin-right: 0;
    margin-bottom: 8px;
  }

  .table-card {
    overflow-x: auto;
  }
}
</style>
